from django.db import models
from django.contrib.auth.models import AbstractBaseUser,PermissionsMixin,BaseUserManager
from django.contrib.auth.hashers import make_password
from shortuuidfield import ShortUUIDField


class ChoiceUserStatus(models.IntegerChoices):
    # 已经激活
    ACTIVE = 1
    # 还没有激活
    UNACTIVE = 2
    # 被锁定
    LOCK = 3

class OAManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, realname, email, password, **extra_fields):
        """
        创建一个用户.
        """
        if not realname:
            raise ValueError("必须设置真实姓名")
        email = self.normalize_email(email)
        # 这里相当于是获取了 调用此方法的模型类 OAUser
        user = self.model(realname=realname, email=email, **extra_fields)
        user.password = make_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, realname, email=None, password=None, **extra_fields):
        """
        创建普通用户
        :param realname:
        :param email:
        :param password:
        :param extra_fields:
        :return:
        """
        extra_fields.setdefault("is_staff", True)
        extra_fields.setdefault("is_superuser", False)
        return self._create_user(realname, email, password, **extra_fields)

    def create_superuser(self, realname, email=None, password=None, **extra_fields):
        """
        创建超级用户
        :param realname:
        :param email:
        :param password:
        :param extra_fields:
        :return:
        """
        extra_fields.setdefault("is_staff", True)
        extra_fields.setdefault("is_superuser", True)
        extra_fields.setdefault("status",ChoiceUserStatus.ACTIVE)

        if extra_fields.get("is_staff") is not True:
            raise ValueError("超级用户必须设置is_statff=True")
        if extra_fields.get("is_superuser") is not True:
            raise ValueError("超级用户必须设置is_superuser=True.")

        return self._create_user(realname, email, password, **extra_fields)

# Create your models here.
class OAUser(AbstractBaseUser,PermissionsMixin):
    """
    自定义User模型
    """
    # 唯一的字符串作为表的主键
    uid = ShortUUIDField(primary_key=True)
    realname = models.CharField(max_length=150,unique=False)
    email = models.EmailField(unique=True,blank=False)
    telephone = models.CharField(max_length=20,blank=True)
    is_staff = models.BooleanField(default=True)
    # 只需要关注status即可 无须关注is_active
    status = models.IntegerField(choices=ChoiceUserStatus,default=ChoiceUserStatus.UNACTIVE)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(auto_now_add=True)

    department = models.ForeignKey('OADepartment',null=True,on_delete=models.SET_NULL,related_name='staffs',related_query_name='staffs')

    # User.objects.all() 这里的objects就是这个objects
    objects = OAManager()

    EMAIL_FIELD = "email"
    # USERNAME_FIELD 是用来做鉴权的
    from django.contrib.auth import authenticate
    # from django.contrib.auth import authenticate authenticate这个函数就是用来做鉴权  在内部的authenticate函数使用的username 和password做鉴权
    # 而那个内部的username是用过这里的USERNAME_FIELD这个字段获取的值
    USERNAME_FIELD = "email"
    # 指定哪些字段是必须要传的 但是不包含USERNAME_FIELD和EMAIL_FIELD字段的值
    REQUIRED_FIELDS = ["realname","password"]

    # class Meta:
    #     # 使用django中自带的admin系统中使用的 verbose_name verbose_name_plural
    #     # verbose_name = _("user")
    #     # verbose_name_plural = _("users")
    #     # abstract = True 不会把这个模型同步到数据库当中
    #     abstract = True

    def clean(self):
        super().clean()
        self.email = self.__class__.objects.normalize_email(self.email)

    def get_full_name(self):
        return self.realname

    def get_short_name(self):
        return self.realname


class OADepartment(models.Model):
    name = models.CharField(max_length=100)
    intro = models.CharField(max_length=200)
    # leader
    # related_query_name跨表查询用到
    leader = models.OneToOneField(OAUser,null=True,on_delete=models.SET_NULL,related_name='leader_department',related_query_name='leader_department')
    # manager
    manager = models.ForeignKey(OAUser,null=True,on_delete=models.SET_NULL,related_name='manager_departments',related_query_name='manager_departments')